/**
 * @author Tobias Boehm
 *
 * 29.03.2011
 */
package org.anddev.andengine.extension.tbsengine.gameobject;

import java.util.HashMap;
import java.util.UUID;

import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.extension.tbsengine.match.gamestate.AbsPlayerGameState;

/**
 * This class represents a factory producing {@link Unit}s. You will
 * need one instance for your game server and one instance for each client.
 * <p>
 * Manual:<br>
 * To create new units call {@link #createNewUnit(String, AbsPlayerGameState)}.<br>
 * To create existing units (those are units which where created by another client
 * or by the game server) call {@link #createKnownUnit(String, AbsPlayerGameState, UUID)}.<br>
 *  
 * @author Tobias Boehm
 *
 */
public class UnitFactory {
	
	private static final HashMap<String,UnitType> sUnitTypeCache = new HashMap<String, UnitType>();
	
	
	private final Engine mEngine;
		
	
	public UnitFactory(final Engine pEngine){
		
		this.mEngine = pEngine;
	}
				
	public Unit createNewUnit(final String pUnitType, final AbsPlayerGameState pOwner){
		
		// Generate unique unit ID
		final UUID unitId = UUID.randomUUID();
		
		return this.createKnownUnit(pUnitType, pOwner, unitId);
	}
	
	public Unit createKnownUnit(final String pUnitType, final AbsPlayerGameState pOwner, final UUID unitId){
		
		// Load unit type if this not happened before
		if(!sUnitTypeCache.containsKey(pUnitType)){
			
			this.loadUnitType(pUnitType);	
		}

		// Determine UnitTpye
		final UnitType unitType = sUnitTypeCache.get(pUnitType);
		
		// Create Unit
		final Unit unit = new Unit(unitType, pOwner, unitId);
		
		
		return unit;
	}

	private void loadUnitType(String pUnitType) {
		// TODO: Load unit from xml
	
		throw new IllegalArgumentException("Unittype not found");
	}
	
	public void unloadUnitType(final UnitType pUnitType){
		
		sUnitTypeCache.remove(pUnitType.mID);
		
		this.mEngine.getTextureManager().unloadTextures(pUnitType.getTexture());	
	}
}
